import React, {useEffect, useState} from 'react';
import {Button, Select, Input, Table, Space, Pagination, Tag, Modal, Popconfirm, notification} from "antd";
import http from "../request";

import Header from "../components/Header";
import Footer from "../components/Footer";
import Recycle from "../components/Recycle";
// --------------------
import Menu from "../components/Menu1"

import {fieldGet, paramChange} from "../common/common";
import { store } from '../store';


const { Option } = Select;

const City = () => {
    const field = {level: '=', name: 'like'}
    const pagerDefault = {page: 1, pageSize: 10}
    const editDefault = {
        id: '',
        level: 'city',
        pid: 0,
        name: ''
    }
    const [page, setPage] = useState(pagerDefault)
    const [total, setTotal] = useState(0)
    const [form, setForm] = useState({
        level: '',
        name: ''
    })
    const [source, setSource] = useState([])
    const [columns] = useState([
        {
            title: 'id',
            dataIndex: 'id',
            key: 'id',
            align: 'center',
        }, 
        // {
        //     title: '上级',
        //     key: 'pid',
        //     align: 'center',
        //     render: text => text?.pid_data ? text.pid_data.name : '无'
        // }
        // , {
        //     title: '类型',
        //     dataIndex: 'level',
        //     key: 'level_text',
        //     align: 'center',
        //     render: text => {
        //         switch(text){
        //             case 'city':
        //                 return <Tag color="red">城市</Tag>;
        //             case 'region':
        //                 return <Tag color="green">地区</Tag>
        //             case 'area':
        //                 return <Tag color="blue">片区</Tag>
        //             default:
        //                 return '无'
        //         }
        //     },
        // },
        {
            title: '片区名称',
            dataIndex: 'name',
            key: 'name',
            align: 'center',
        }, {
            title: '操作',
            key: 'action',
            align: 'center',
            render: e => (
                <Space size="middle">
                    <img className="u-btn" src={require('../assets/icon/icon-12.png').default} alt="" title="编辑" onClick={() => (!(system?.cspq_xg?.value?? 1))?setcdd(!0):editModal(e.id)}/>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={() => (!(system?.cspq_sc?.value?? 1))?setcdd(!0):del(e.id)}>
                        <img className="u-btn" src={require('../assets/icon/icon-13.png').default} alt="" title="删除"/>
                    </Popconfirm>
                </Space>
            ),
        }
    ])
    const [select, setSelect] = useState([])
    const [editForm, setEditForm] = useState(editDefault)
    const [show, setShow] = useState(!1)
    const [list, setList] = useState([])

    //-------------------------------------------------------------
    // 城区-树状
    const [menuKeys, setMenuKeys] = useState([])

    const [cdd,setcdd] = useState(!1)
    let {system} = {system:undefined}
    if(store.getState().userInfo.group_id !== 3){
        system=store.getState().staff.system
    }

    const [change, setchange] = useState(!0)
    // 回收站栏目
    const backColumns = [
        {
            title: 'id',
            dataIndex: 'id',
            key: 'id',
        }, {
            title: '上级',
            key: 'pid',
            render: text => text?.pid_data ? text.pid_data.name : '无'
        }, {
            title: '类型',
            dataIndex: 'level',
            key: 'level_text',
            render: text => {
                switch(text){
                    case 'city':
                        return <Tag color="red">城市</Tag>;
                    case 'region':
                        return <Tag color="green">地区</Tag>
                    case 'area':
                        return <Tag color="blue">片区</Tag>
                    default:
                        return '无'
                }
            },
        }, {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        }
    ]

    // const [mask, setMask] = useState({show: !1, text: ''})

    // ------------------------------
    useEffect(() => {
        getList()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [page,menuKeys])

    useEffect(() => {
        !show && setEditForm(editDefault)
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [show])
    return (
        <React.Fragment>
            <Header navCur={0}/>
            <div className="City page u-m-20 u-p-20">
                <div className="part-title">城市片区</div>
                <div className="u-flex u-row-between u-m-t-20">
                    <Recycle url='city' func={getList} columns={backColumns} change={setchange}/>
                    <div className="u-flex">
                        <Select showSearch placeholder="级别" value={form.level} onChange={e => paramChange(setForm, form, 'level', e)} style={{width: 120}}>
                            <Option value="">全部</Option>
                            <Option value="city">城市</Option>
                            <Option value="region">地区</Option>
                            <Option value="area">片区</Option>
                        </Select>
                        <Input placeholder="名称" value={form.name} onChange={e => paramChange(setForm, form, 'name', e.target.value)} className="u-m-l-10" style={{width: 200}} />
                        <Button type="primary" onClick={getList}>
                            <img src={require('../assets/icon/icon-6.png').default} alt="" />
                        </Button>
                        <div className="u-btn u-flex u-m-l-20" onClick={reset}>
                            <img src={require('../assets/icon/icon-7.png').default} alt="" />
                            <span className="u-m-l-5 u-text-nowrap">清空</span>
                        </div>
                    </div>
                </div>
                <div className='u-m-t-20 u-flex u-col-top '>
                    {/* 导航栏 */}
                    <Menu menuKeys={menuKeys} menuChange={menuChange}/>

                        <Table sticky bordered size="small" rowSelection={{
                            selectedRowKeys: select,
                            onChange: (e) => {
                                setSelect(e)
                            }
                        }} rowKey={e => e.id} onRow={e => ({
                            onDoubleClick: () => {
                                editModal(e.id)
                            }
                        })} dataSource={source} columns={columns} pagination={false} />
                </div>
                <div className="u-flex u-row-between u-m-t-20">
                    <div>
                        <Button type="primary" size="small" onClick={() => (!(system?.cspq_ck?.value?? 1))?setcdd(!0):setShow(!0)}>
                            <div className="u-flex">
                                <img src={require('../assets/icon/icon-18.png').default} alt=""/>
                                <span className="u-m-l-5">新增</span>
                            </div>
                        </Button>
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={del}>
                            <Button className="u-m-l-20" type="primary" size="small" danger>
                                <div className="u-flex">
                                    <img src={require('../assets/icon/icon-19.png').default} alt=""/>
                                    <span className="u-m-l-5">删除</span>
                                </div>
                            </Button>
                        </Popconfirm>
                    </div>
                    <Pagination showQuickJumper current={page.page} pageSize={page.pageSize} total={total} onChange={(page, pageSize) => setPage({page, pageSize})} />
                </div>
            </div>
            <Footer/>
            <Modal title="城市片区" width={290} visible={show} onOk={confirm} onCancel={() => setShow(!1)}>
                <div className="Modal">
                    <div className="u-flex">
                        <div className="label">级别</div>
                        <Select showSearch placeholder="级别" value={editForm.level} onChange={e => editCity(e)} className="u-m-l-10" style={{width: 200}}>
                            <Option value="city">城市</Option>
                            <Option value="region">地区</Option>
                            <Option value="area">片区</Option>
                        </Select>
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">上级</div>
                        <Select showSearch placeholder="城市片区" value={editForm.pid} onChange={e => paramChange(setEditForm, editForm, 'pid', e)} className="u-m-l-10" style={{width: 200}}>
                            <Option value={0}>无</Option>
                            {
                                list.map((e, i) => <Option value={e.id} key={e.id}>{e.name}</Option>)
                            }
                        </Select>
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">名称</div>
                        <Input placeholder="名称" value={editForm.name} onChange={e => paramChange(setEditForm, editForm, 'name', e.target.value)} className="u-m-l-10" style={{width: 200}} />
                    </div>
                </div>
            </Modal>
            <Modal title="提示" footer={false} visible={cdd} onCancel={() => setcdd(!1)}>
                <h3>权限不足</h3>
            </Modal>
        </React.Fragment>
    )

    // *-------------------------------------------
    function menuChange(
        id, 
        city, 
        region, 
        area
        ){
            console.log(region);
            if(!region)return getList()
        setSource(source.filter(i=>i.pid === region))
        // let newForm = JSON.parse(JSON.stringify(form))
        // newForm.city = city
        // newForm.region = region
        // newForm.area = area
        // setForm(newForm)
        // setMenuKeys(['city-'+id])
    }

    // --------------------------点击-------------------------------------------
    function getList(form = {}){
        if(!(system?.cspq_ck?.value?? 1)) return setcdd(!0)
        if(change && JSON.parse(sessionStorage.getItem('city_list'))){
            const house = JSON.parse(sessionStorage.getItem('city_list'))
            for (const key in house.rows) {
                if (key*1 === page.page) {
                    setSource(house.rows[key])
                    setTotal(house.total)
                    return
                }
            }
        }
        http('city.index' ,
            fieldGet(
                field,
                form,
                page.page,
                page.pageSize
            ),
        ).then(res => {
            if(res.code === 1){
                console.log(res);
                const pager = page.page
                if(total && change){
                    let arr = JSON.parse(sessionStorage.getItem('city_list'))
                    arr.rows[pager] = []
                    res.data.rows.forEach(i=>arr.rows[pager].push(i))
                    sessionStorage.setItem('city_list',JSON.stringify(arr))
                    setchange(!0)
                    setSource(res.data.rows)
                    setTotal(res.data.total)
                    return
                }
                const data = {
                    total:res.data.total,
                    rows:{
                        [pager]:res.data.rows
                    }
                }
                sessionStorage.setItem('city_list',JSON.stringify(data))
                setchange(!0)
                setSource(res.data.rows)
                setTotal(res.data.total)
            }
                
        }).catch(err=>console.log(err))
    }
    function reset(){
        setForm({level: '', name: ''})
        setPage(pagerDefault)

        // ----------------
        setMenuKeys([])

    }
    function cityChange(level){
        if (level !== 'city') {
            http('city.index', {
                filter: JSON.stringify({level}),
                op: JSON.stringify({level: '='}),
            }).then(res => {
                if(res.code === 1){
                    // console.log(res.data,"城市上级0000");
                    setList(res.data.rows)
                }
            })
        }else{
            let data = []
            setList(data)
        }
       
    }
    function del(id){
        // console.log(1);
        if(!(system?.cspq_sc?.value?? 1)) return setcdd(!0)
        let ids = id > 0 ? [id] : select
        http('city.del', {ids}).then(res => {
            setchange(!1)
                getList()
        })
    }
    function editModal(id){
        http('city.index', {
            filter: JSON.stringify({id}),
            op: JSON.stringify({id: '='}),
        }).then(res => {
            if(res.code === 1){
                let data = res.data.rows[0]
                setEditForm(data)
                let arr = {'city': '', 'region': 'city', 'area': 'region'}
                cityChange(arr[data.level])
                setShow(!0)
            }
        })
    }
    function editCity(level){
        paramChange(setEditForm, editForm, 'level', level)
        cityChange(level)
    }
    function confirm(){
        let url = editForm?.id ? 'city.edit' : 'city.add'
        http(url, {
            row: editForm
        }).then(res => {
            if(res.code === 1){
                notification.success({
                    message: res.msg || '操作成功'
                })
                setchange(!1)
                setEditForm(editDefault)
                setShow(!1)
                getList()
            } else {
                notification.error({
                    message: res.msg || '操作失败，请重试'
                })
            }
            // setMask({show: !1, text: ''})
        })
    }
}

export default City;